package com.bosc.automationui.service;

import com.bosc.automationui.entity.ETLJob;
import com.bosc.automationui.entity.JobHistory;
import com.bosc.automationui.repository.ETLJobRepository;
import com.bosc.automationui.repository.JobHistoryRepository;
import com.bosc.automationui.util.StringToDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class JobService {

    @Autowired
    JobHistoryRepository jobHistoryRepository;

    @Autowired
    ETLJobRepository etlJobRepository;

    public HashMap<String, Object> sync() {

        HashMap<String, Object> responseJson = new HashMap<>();
//        Iterable<ETLJobStatus> etlJobStatuses = etlJobStatusRepository.findAll();
        List<String> etlJobStatusIncrements = etlJobRepository.getJobStatusIncrement();
        System.out.println("JobService.sync()");
        System.out.println("etlJobStatusIncrements -> " + etlJobStatusIncrements);
        if (etlJobStatusIncrements != null) {
            for (String row : etlJobStatusIncrements) {
                String[] rowSplits = row.split(",");
                System.out.println("rowSplits.toString() -> " + rowSplits.toString());
                JobHistory jobHistory = new JobHistory(
                        null,
                        10000L,
                        rowSplits[0],
                        rowSplits[1],
                        StringToDateUtil.strToDate(rowSplits[13]),
                        "TEST",
                        "TESTOP",
                        rowSplits[12]);
                System.out.println("job.toString() -> " + jobHistory.toString());
                jobHistoryRepository.save(jobHistory);
            }
            responseJson.put("code", "0");
            responseJson.put("message", "success");
        } else {
            responseJson.put("code", "0");
            responseJson.put("message", "noting new added");
        }

        return responseJson;
    }

    public HashMap<String, Object> getOverview() {

        HashMap<String, Object> responseJson = new HashMap<>();
        HashMap<String, Object> pie = new HashMap<>();
        List<ETLJob> tPlus;

        // pie
        int runningJobs = 0;
        int doneJobs = 0;
        int failedJobs = 0;
        int pendingJobs = 0;

        Iterable<JobHistory> jobList = jobHistoryRepository.findAllByOrderByTxDateDesc();
        List<ETLJob> pieJobList = etlJobRepository.getAllToday();

        for (ETLJob jobHistory : pieJobList) {
            switch (jobHistory.getLastJobStatus().toLowerCase()) {
                case ("failed"):
                    failedJobs++;
                    break;
                case ("running"):
                    runningJobs++;
                    break;
                case ("done"):
                    doneJobs++;
                    break;
                case ("pending"):
                    pendingJobs++;
                    break;
            }
        }

        pie.put("running", runningJobs);
        pie.put("done", doneJobs);
        pie.put("failed", failedJobs);
        pie.put("pending", pendingJobs);


        // tplus
        tPlus = etlJobRepository.getTPlus();

        responseJson.put("code", "0");
        responseJson.put("message", "success");
        List<ETLJob> finalTPlus = tPlus;
        responseJson.put("data", new HashMap<String, Object>() {
            {
                put("job_list", jobList);
                put("trending", getTrendingData());
                put("pie", pie);
                put("t_plus", finalTPlus);
            }
        });

        return responseJson;
    }


    /**
     * @return
     */
    //todo: to be refactored
    public HashMap<String, HashMap<String, String>> getTrendingData() {
        HashMap<String, HashMap<String, String>> trendingData = new HashMap<String, HashMap<String, String>>();
        trendingData.put("today", processTrendingData(etlJobRepository.getTodayTrending()));
        trendingData.put("yesterday", processTrendingData(etlJobRepository.getYesterdayTrending()));
        return trendingData;
    }

    public HashMap<String, HashMap<String, String>> testTrendingData(ArrayList<String> yesterday, ArrayList<String> today) {
        HashMap<String, HashMap<String, String>> trendingData = new HashMap<String, HashMap<String, String>>();
        trendingData.put("today", processTrendingData(yesterday));
        trendingData.put("yesterday", processTrendingData(today));
        return trendingData;
    }

    //        List<String> trendingRows;
//        HashMap<String, Integer> trendingResultMap = new HashMap<>();
//        trendingRows = etlJobRepository.getTodayTrending();
//        HashMap<String, Integer> trendingRowsMap = new HashMap<>();
//        List<String> hoursNotFound = new ArrayList<>();
//        int lastKnownSum = 0;
//
//        for (String row : trendingRows) {
//            String[] values = row.split(",");
//            trendingRowsMap.put(Integer.valueOf(values[0]).toString(), Integer.valueOf(values[1]));
//        }
//        /**
//         * initialize the hashmap,
//         * in this map the key is the hour ranging from 0 to 23
//         * the value is the sum of job number that already finished.
//         * In the initial map, all values are 0.
//         */
//        for (int i = 0; i < 24; i++) {
//            trendingResultMap.put(String.valueOf(i), 0);
//        }
//
//        /**
//         * The process of constructing a hashmap where the value
//         * is the accumulate sum of job number till the hour of the day.
//         */
//        for (int i = 0; i < 24; i++) {
//            String hour = String.valueOf(i);
//            if (trendingRowsMap.containsKey((hour))) {
//                if (hoursNotFound.size() > 0) {
//                    for (String aHour : hoursNotFound) {
//                        trendingResultMap.put(aHour, lastKnownSum);
//                    }
//                    hoursNotFound.clear();
//                }
//                trendingResultMap.put(hour, trendingRowsMap.get(hour));
//                lastKnownSum = trendingRowsMap.get(hour);
//            } else {
//                hoursNotFound.add(hour);
//            }
//        }
//
//        //增加逻辑补充数据库不存在的小时的数据
//        Date date = new Date();
//        SimpleDateFormat format = new SimpleDateFormat("HH");
//        String currentHour = format.format(date);
//        ArrayList<String> keyList = new ArrayList<>();
//        for(Map.Entry<String,Integer> entry : trendingResultMap.entrySet())
//            if(entry.getValue() != 0)
//                keyList.add(entry.getKey());
//        Collections.sort(keyList);
//        int lastHourAvail = Integer.valueOf(keyList.get(keyList.size() - 1));
//        if(Integer.valueOf(currentHour) > lastHourAvail)
//        {
//            for (int i = lastHourAvail; i <= Integer.valueOf(currentHour);i++) {
//                trendingResultMap.put(String.valueOf(i),lastKnownSum);
//            }
//        }
//
//
//        return trendingResultMap;
//    }
    public HashMap<String, String> processTrendingData(List<String> trendingRows) {
        HashMap<String, String> trendingResultMap = new HashMap<>();
        HashMap<String, Integer> trendingRowsMap = new HashMap<>();
        List<String> hoursNotFound = new ArrayList<>();
        int lastKnownSum = 0;

        for (String row : trendingRows) {
            String[] values = row.split(",");
            trendingRowsMap.put(Integer.valueOf(values[0]).toString(), Integer.valueOf(values[1]));
        }
        /**
         * initialize the hashmap,
         * in this map the key is the hour ranging from 0 to 23
         * the value is the sum of job number that already finished.
         * In the initial map, all values are 0.
         */
        for (int i = 0; i < 24; i++) {
            trendingResultMap.put(String.valueOf(i), "0");
        }

        /**
         * The process of constructing a hashmap where the value
         * is the accumulate sum of job number till the hour of the day.
         */
        for (int i = 0; i < 24; i++) {
            String hour = String.valueOf(i);
            if (trendingRowsMap.containsKey((hour))) {
                if (hoursNotFound.size() > 0) {
                    for (String aHour : hoursNotFound) {
                        trendingResultMap.put(aHour, String.valueOf(lastKnownSum));
                    }
                    hoursNotFound.clear();
                }
                trendingResultMap.put(hour, String.valueOf(trendingRowsMap.get(hour)));
                lastKnownSum = trendingRowsMap.get(hour);
            } else {
                hoursNotFound.add(hour);
            }
        }

        //增加逻辑补充数据库不存在的小时的数据
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("HH");
        String currentHour = format.format(date);
        ArrayList<Integer> keyList = new ArrayList<>();
        for (Map.Entry<String, String> entry : trendingResultMap.entrySet())
            if (entry.getValue() != "0")
                keyList.add(Integer.valueOf(entry.getKey()));
        Collections.sort(keyList);
        if (keyList.size() != 0) {
            int lastHourAvail = keyList.get(keyList.size() - 1);
            if (Integer.valueOf(currentHour) > lastHourAvail) {
                for (int i = lastHourAvail; i <= Integer.valueOf(currentHour); i++) {
                    trendingResultMap.put(String.valueOf(i), String.valueOf(lastKnownSum));
                }

            }
        }
        //增加当前时间字符串标记
        trendingResultMap.put(currentHour, trendingResultMap.get(currentHour) + ",当前时间");


        return trendingResultMap;
    }
//    public HashMap<String, Integer> testTrendingData(List<String> trendingRows) {
//
//        HashMap<String, Integer> trendingResultMap = new HashMap<>();
//        HashMap<String, Integer> trendingRowsMap = new HashMap<>();
//        List<String> hoursNotFound = new ArrayList<>();
//        int lastKnownSum = 0;
//
//        for (String row : trendingRows) {
//            String[] values = row.split(",");
//            trendingRowsMap.put(Integer.valueOf(values[0]).toString(), Integer.valueOf(values[1]));
//        }
//        /**
//         * initialize the hashmap,
//         * in this map the key is the hour ranging from 0 to 23
//         * the value is the sum of job number that already finished.
//         * In the initial map, all values are 0.
//         */
//        for (int i = 0; i < 24; i++) {
//            trendingResultMap.put(String.valueOf(i), 0);
//        }
//
//        /**
//         * The process of constructing a hashmap where the value
//         * is the accumulate sum of job number till the hour of the day.
//         */
//        for (int i = 0; i < 24; i++) {
//            String hour = String.valueOf(i);
//            if (trendingRowsMap.containsKey((hour))) {
//                if (hoursNotFound.size() > 0) {
//                    for (String aHour : hoursNotFound) {
//                        trendingResultMap.put(aHour, lastKnownSum);
//                    }
//                    hoursNotFound.clear();
//                }
//                trendingResultMap.put(hour, trendingRowsMap.get(hour));
//                lastKnownSum = trendingRowsMap.get(hour);
//            } else {
//                hoursNotFound.add(hour);
//            }
//        }
//
//        //增加逻辑补充数据库不存在的小时的数据
//        Date date = new Date();
//        SimpleDateFormat format = new SimpleDateFormat("HH");
//        String currentHour = format.format(date);
//        ArrayList<String> keyList = new ArrayList<>();
//        for(Map.Entry<String,Integer> entry : trendingResultMap.entrySet())
//            if(entry.getValue() != 0)
//                keyList.add(entry.getKey());
//        Collections.sort(keyList);
//        int lastHourAvail = Integer.valueOf(keyList.get(keyList.size() - 1));
//        if(Integer.valueOf(currentHour) > lastHourAvail)
//        {
//            for (int i = lastHourAvail; i <= Integer.valueOf(currentHour);i++) {
//                trendingResultMap.put(String.valueOf(i),lastKnownSum);
//            }
//        }
//
//
//        return trendingResultMap;
//    }

}
